//
//  TravelNotesViewController.m
//  BeanTrip
//
//  Created by dlios on 15-6-30.
//  Copyright (c) 2015年 PandaGroup. All rights reserved.
//

#import "TravelNotesViewController.h"
#define WIDTH ([UIScreen mainScreen].bounds.size.width/375)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height/667)
#import "HTTPTool.h"
#import "TravelNotesDetailModel.h"
#import "UserModel.h"
#define WIDTHIMAGE self.coverImageView.frame.size.width
#define HEIGTHIMAGE self.coverImageView.frame.size.height
#import "UIImageView+WebCache.h"
#import "daysModel.h"
#import "TextImageCell.h"
#import "PhotoViewController.h"
#import "MBProgressHUD.h"



@interface TravelNotesViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UIView *headerView;
@property(nonatomic, retain)UILabel *nameLabel;
@property(nonatomic, retain)UILabel *day_countLabel;
@property(nonatomic, retain)UILabel *mileageLabel;
@property(nonatomic, retain)UILabel *userLabel;
@property(nonatomic, retain)UILabel *flightLabel;
@property(nonatomic, retain)UILabel *hotelLabel;
@property(nonatomic, retain)UILabel *sightsLabel;
@property(nonatomic, retain)UILabel *restaurantLabel;
@property(nonatomic, retain)UIImageView *coverImageView;
@property(nonatomic, retain)NSMutableArray *countryImageArr;
@property(nonatomic, retain)UIView *backgroundView;
@property(nonatomic, retain)NSMutableArray *nameArr;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, retain)NSMutableArray *photoImageArr;
@property(nonatomic, retain)NSMutableArray *titleSectionArr;
@property(nonatomic, retain)NSMutableArray *daysTitleArr;
@property(nonatomic, retain)UIAlertView *alert;
@property(nonatomic, retain)UIView *bacView;


@end

@implementation TravelNotesViewController
- (void)dealloc
{
    [_detailId release];
    [_titleName release];
    [_headerView release];
    [_tableView release];
    [_nameLabel release];
    [_day_countLabel release];
    [_mileageLabel release];
    [_userLabel release];
    [_flightLabel release];
    [_hotelLabel release];
    [_sightsLabel release];
    [_restaurantLabel release];
    [_coverImageView release];
    [_countryImageArr release];
    [_photoImageArr release];
    [_backgroundView release];
    [_titleSectionArr release];
    [_daysTitleArr release];
    [_nameArr release];
    [_HUD release];
    [_photoImageArr release];
    [_alert release];
    [_bacView release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
        
    
    //右上角的相册
    UIImage *albumImage = [UIImage imageNamed:@"iconfont-xiangce"];
    albumImage = [albumImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:albumImage style:UIBarButtonItemStylePlain target:self action:@selector(clickAlbum:)];
    
    
    self.title = self.titleName;
    
    //新建一个tableview,作为主视图,上面放一个view名为headerview
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375*WIDTH, 667*HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [_tableView release];

    
    //新建头视图,view
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375*WIDTH, HEIGHT*667 / 3 + HEIGHT*667 / 5 + 20)];
    [self.view addSubview:self.headerView];
    [_headerView release];
    self.tableView.tableHeaderView = self.headerView;
    
    
    //背景视图用于遮挡请求数据前的视图
    self.bacView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375*WIDTH, 667*HEIGHT)];
    self.bacView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bacView];
    [_bacView release];

    
    
    /**
     小菊花
     
     :returns: 是
     */
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];
    
    
    [self createView];    
    [self createData];
}

- (void)createView
{
    //背景图片
    self.coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH*375 , HEIGHT*667 / 3 )];
    [self.headerView addSubview:self.coverImageView];
    [_coverImageView release];
    
    
    //标题
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 5*HEIGHT, WIDTHIMAGE - 80, HEIGTHIMAGE / 3)];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.numberOfLines = 0;
    self.nameLabel.textColor = [UIColor whiteColor];
    //4.设置文字类型与大小
    self.nameLabel.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20*HEIGHT];
    [self.coverImageView addSubview:self.nameLabel];
    [_nameLabel release];
    
    
    
    //开始时间持续时间
    self.day_countLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*WIDTH, HEIGTHIMAGE / 2 - 10*HEIGHT, WIDTH*375 - 40*WIDTH, HEIGTHIMAGE / 4)];
    self.day_countLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    self.day_countLabel.textColor = [UIColor whiteColor];
    [self.coverImageView addSubview:self.day_countLabel];
    [self.day_countLabel release];
    
    //里程
    self.mileageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*WIDTH, HEIGTHIMAGE / 2+20*HEIGHT, WIDTH*375 - 40, HEIGTHIMAGE / 4)];
    self.mileageLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    self.mileageLabel.textColor = [UIColor whiteColor];
    [self.coverImageView addSubview:self.mileageLabel];
    [self.mileageLabel release];
    
    //user
    self.userLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGTHIMAGE - 30, WIDTHIMAGE - 20, 20)];
    self.userLabel.textAlignment = NSTextAlignmentRight;
    self.userLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    self.userLabel.textColor = [UIColor whiteColor];
    [self.coverImageView addSubview:self.userLabel];
    [self.userLabel release];
    
    
    //里程信息
    UIButton *backgroundButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backgroundButton.frame = CGRectMake(20*WIDTH, 10 + HEIGTHIMAGE, WIDTH*375 - 40, HEIGHT*667 / 5);
    [self.headerView addSubview:backgroundButton];
    
    

    //button上的view
    self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, backgroundButton.frame.size.width, backgroundButton.frame.size.height)];
    self.backgroundView.backgroundColor = [UIColor colorWithRed:231 / 255.0 green:211 / 255.0 blue:201 / 255.0 alpha:1];
    self.backgroundView.layer.cornerRadius = 10;
    [backgroundButton addSubview:self.backgroundView];
    [_backgroundView release];
    //小图标
    //1.航班
    UIImageView *flightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"机票lm.png"]];
    flightImageView.frame = CGRectMake(10*WIDTH, 0, 30*WIDTH, self.backgroundView.frame.size.height/4);
    [self.backgroundView addSubview:flightImageView];
    [flightImageView release];
    

    self.flightLabel = [[UILabel alloc] initWithFrame:CGRectMake(50*WIDTH, 0, 80*WIDTH, self.backgroundView.frame.size.height/4)];
    self.flightLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    [self.backgroundView addSubview:self.flightLabel];
    [_flightLabel release];
    
    //2.住宿
    UIImageView *hotelImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"酒店lm"]];
    hotelImageView.frame = CGRectMake(187*WIDTH , 0, 30*WIDTH, self.backgroundView.frame.size.height/4);
    [self.backgroundView addSubview:hotelImageView];
    [hotelImageView release];
    
    
    self.hotelLabel = [[UILabel alloc] initWithFrame:CGRectMake(230*WIDTH, 0, 80*WIDTH, self.backgroundView.frame.size.height/4)];
    self.hotelLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    [self.backgroundView addSubview:self.hotelLabel];
    [_hotelLabel release];

    //3.景点
    UIImageView *sightsImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"景点"]];
    sightsImageView.frame = CGRectMake(10*WIDTH, self.backgroundView.frame.size.height/3, 30*WIDTH, self.backgroundView.frame.size.height/4);
    [self.backgroundView addSubview:sightsImageView];
    [sightsImageView release];
    
    
    self.sightsLabel = [[UILabel alloc] initWithFrame:CGRectMake(50*WIDTH, self.backgroundView.frame.size.height/3, 80*WIDTH, self.backgroundView.frame.size.height/4)];
    self.sightsLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    [self.backgroundView addSubview:self.sightsLabel];
    [_sightsLabel release];

    //4.餐饮
    UIImageView *restaurantImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"美食"]];
    restaurantImageView.frame = CGRectMake(187*WIDTH, self.backgroundView.frame.size.height/3, 30*WIDTH, self.backgroundView.frame.size.height/4);
    [self.backgroundView addSubview:restaurantImageView];
    [restaurantImageView release];
    
    
    self.restaurantLabel = [[UILabel alloc] initWithFrame:CGRectMake(230*WIDTH, self.backgroundView.frame.size.height/3, 80*WIDTH, self.backgroundView.frame.size.height/4)];
    self.restaurantLabel.font = [UIFont systemFontOfSize:17*HEIGHT];
    [self.backgroundView addSubview:self.restaurantLabel];
    [_restaurantLabel release];
    
    
}


//解析数据
- (void)createData
{
    //拼接网址
    NSString *detailUrl = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?gallery_mode=1&sign=201d8d1f4f0cb5f3ec04952314a7d3ef",self.detailId];
    
    [HTTPTool get:detailUrl body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        TravelNotesDetailModel *travelNote = [[TravelNotesDetailModel alloc] initWithDic:dic];
        
        //给headerview赋值
        self.nameLabel.text = travelNote.name;
        //description强制转换成字符串类型[travelNote.name description]

        //时间天数
        NSString *dayCount = [NSString stringWithFormat:@"%@  共%@天",travelNote.first_day,travelNote.day_count];
        self.day_countLabel.text = dayCount;
        
        NSString *mileageCount = [NSString stringWithFormat:@"里程: %ld km",(long)travelNote.mileage];
        self.mileageLabel.text = mileageCount;
        
        //userModel
        NSDictionary *userDic = dic[@"user"];
        UserModel *user = [[UserModel alloc] initWithDic:userDic];
        NSString *byName = [NSString stringWithFormat:@"本游记由%@提供",user.name];
        self.userLabel.text = byName;
        [user release];
        
        //最上面的背景图片
        [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:travelNote.cover_image]];
        
        //为button的四个label赋值
        NSDictionary *poi_infos_countDic = dic[@"poi_infos_count"];
        self.flightLabel.text = [NSString stringWithFormat:@"%@航班",poi_infos_countDic[@"flight"]];
        self.hotelLabel.text = [NSString stringWithFormat:@"%@住宿",poi_infos_countDic[@"hotel"]];
        self.sightsLabel.text = [NSString stringWithFormat:@"%@景点",poi_infos_countDic[@"sights"]];
        self.restaurantLabel.text = [NSString stringWithFormat:@"%@餐饮",poi_infos_countDic[@"restaurant"]];
      
        
        //为下面的国旗赋值
        
        //下面路途国家的label
        self.countryImageArr = [NSMutableArray array];
        self.countryImageArr = dic[@"covered_countries"];
        //根据数组数目用for循环创建
        
            for (NSInteger j = 0; j< self.countryImageArr.count; j++) {
                //坐标
                UIImageView *countryImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10*WIDTH + j * (self.backgroundView.frame.size.height / 3)*WIDTH, self.backgroundView.frame.size.height/3*2, self.backgroundView.frame.size.height / 4, self.backgroundView.frame.size.height / 4)];
                countryImageView.layer.cornerRadius = self.backgroundView.frame.size.height / 8;
                //隐藏边框
                countryImageView.layer.masksToBounds = YES;
                
                NSDictionary *countrDic = self.countryImageArr[j];
                if (j<6) {
                  [countryImageView sd_setImageWithURL:[NSURL URLWithString:countrDic[@"icon"]]];
                }
                
                
                [self.backgroundView addSubview:countryImageView];
                [countryImageView release];
                
                
            }
        [travelNote release];
        
        //对section即第几天进行解析
        self.nameArr = [NSMutableArray array];
        self.titleSectionArr = [NSMutableArray array];
        self.daysTitleArr = [NSMutableArray array];
        
        NSArray *daysArr = dic[@"days"];
        for (NSDictionary *daysDetailDic in daysArr) {
            //section的题目
            NSString *daysTitle = daysDetailDic[@"day"];
            [self.daysTitleArr addObject:daysTitle];

            NSArray *waypointsArr = daysDetailDic[@"waypoints"];
            if (waypointsArr.count != 0) {
                NSMutableArray *allarray =[NSMutableArray array];
                NSMutableDictionary *dicdic = [NSMutableDictionary dictionary];
                for (NSDictionary *waypointsDic in waypointsArr) {
                    daysModel *daysMo = [[daysModel alloc] initWithDic:waypointsDic];
                    [allarray addObject:daysMo];
                    [daysMo release];
                    
                 //把名字放到数组里
                    if ((NSNull *)waypointsDic[@"poi"] != [NSNull null]) {
                        NSDictionary *poi = waypointsDic[@"poi"];
                        NSString *poiN = poi[@"name"];
                        [self.nameArr addObject:poiN];
                    }else{
                        [self.nameArr addObject:@""];
                    }
                }
                [dicdic setObject:allarray forKey:@"waypoints"];
                [self.titleSectionArr addObject:dicdic];
                
            }
            
        }
        [self.tableView reloadData];
        [self.headerView reloadInputViews];
        self.tableView.tableHeaderView = self.headerView;
        //移除菊花
        [self.HUD removeFromSuperview];
        [self.bacView removeFromSuperview];
        
        
    } failure:^(NSError *error) {
        [self.bacView removeFromSuperview];
        [self.HUD removeFromSuperview];
        self.alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.alert show];
        [self.alert release];
        NSLog(@"%@",error);

     }];
    
     
}


- (void)clickAlbum:(UIButton *)button
{

    PhotoViewController *photo = [[PhotoViewController alloc] init];
    photo.photoImageArr = self.titleSectionArr;
    photo.titleName = self.titleName;
    
    [self.navigationController pushViewController:photo animated:YES];
    [photo release];

}

//tableview的方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleSectionArr.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"第%@天", self.daysTitleArr[section]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableDictionary *dic = [self.titleSectionArr objectAtIndex:section];
    NSMutableArray *array = [dic objectForKey:@"waypoints"];
    return array.count;
    
}
//重用cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     
    static NSString *reuse = @"reuse";
    TextImageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[TextImageCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    
   //解析数据开包
    NSMutableDictionary *titdic = [self.titleSectionArr objectAtIndex:indexPath.section];
    NSMutableArray *array = [titdic objectForKey:@"waypoints"];
    daysModel *Mymed = [array objectAtIndex:indexPath.row];
    
    [cell.myMainImageView sd_setImageWithURL:[NSURL URLWithString:Mymed.photo] ];
    cell.myTextLabel.text = Mymed.text;
    cell.localTimeLabel.text = Mymed.local_time;
    cell.placeLabel.text = self.nameArr[indexPath.row];
     return cell;
    
}
//图片自适应的高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSMutableDictionary *titdic = [self.titleSectionArr objectAtIndex:indexPath.section];
    NSMutableArray *array = [titdic objectForKey:@"waypoints"];
    daysModel *Mymed = [array objectAtIndex:indexPath.row];
    //如果有图片
    if (![Mymed.photo isEqualToString:@""]) {
        
    //计算图片高度
    NSDictionary *heightDic = (NSDictionary *)Mymed.photo_info;
    NSString *heightPho = heightDic[@"h"];
    CGFloat heig = [heightPho integerValue];
    
    NSString *widthPho = heightDic[@"w"];
    CGFloat wid = [widthPho integerValue];
    
    CGFloat picHieght = 375*WIDTH * heig / wid;
    
    //计算文字的高度
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16*HEIGHT],NSFontAttributeName, nil];
    daysModel *Mymed = [array objectAtIndex:indexPath.row];
    CGRect rect = [Mymed.text boundingRectWithSize:CGSizeMake(375*WIDTH - 20*WIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return picHieght + rect.size.height + 40*WIDTH;
    }else{
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16*HEIGHT],NSFontAttributeName, nil];
        
        CGRect rect = [Mymed.text boundingRectWithSize:CGSizeMake(WIDTH*375 - 20*WIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        return rect.size.height + 40*WIDTH;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
